﻿using Api.Core.Auth;
using Api.Core.Common.Cache;
using Api.Core.IServices.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Api.Core.Filter
{
    public class GlobalAuthorizeFilter : IAuthorizationFilter
    {
        private readonly IUserInfoService _userInfoService;
        private readonly IAuthServer _authServer;
        private readonly IRedisCache _redisCache;

        public GlobalAuthorizeFilter(IRedisCache redisCache,
            IAuthServer authServer
            , IUserInfoService userInfoService)
        {
            _userInfoService = userInfoService;
            _authServer = authServer;
            _redisCache = redisCache;
        }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            #region
            var endpoint = context.HttpContext.GetEndpoint();
            if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
            {
                return;
            }
            var token = context.HttpContext.Request.Headers["Authorization"];
            token = token.ToString().Split(' ')[1];
            var tokenModel = _authServer.SerializeJwt(token);

            var result = new JsonResult(new
            {
                success = false,
                message = "认证失败,请重新登陆!"
            });

            var user = _userInfoService.Query(x => x.UserId == tokenModel.UserId && x.IsDel == false);
            if (user.Result.Count == 0)
            {
                result = new JsonResult(new
                {
                    success = false,
                    message = "当前用户已被管理员设置禁止访问,请联系管理员!"
                });
                context.Result = result;
                return;
            }

            if (tokenModel == null)
            {
                context.Result = result;
                return;
            }

            if (string.IsNullOrWhiteSpace(tokenModel.UserId))
            {
                context.Result = result;
                return;
            }
            else
            {
                var isTrue = _redisCache.Get(tokenModel.UserId);
                if (!isTrue)
                {
                    context.Result = result;
                    return;
                }
            }
            #endregion
        }
    }
}
